package archer.framework.common.filter;

import archer.framework.core.constant.Constant;
import archer.framework.protocol.result.ExecuteResultProcessor;
import archer.framework.security.netpolice.SuspiciousEvent;
import archer.framework.security.utils.SubjectUtils;
import archer.framework.security.utils.SuspiciousUtils;
import archer.framework.utils.JSONUtils;
import archer.framework.web.entity.AccessLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * @author christ
 * @date 2016/8/18
 */
public class IpFilter extends archer.framework.web.filter.IpFilter {

    private static Logger logger = LoggerFactory.getLogger(IpFilter.class);

    @Override
    protected void accessDenied(ServletRequest servletRequest, ServletResponse servletResponse) {

        super.accessDenied(servletRequest, servletResponse);

        reportSuspiciousEvent(servletRequest);

        feedBackAccessDenied(servletResponse);
    }

    /**
     * 返回错误信息
     *
     * @param servletResponse
     */
    protected void feedBackAccessDenied(ServletResponse servletResponse) {
        try {
            servletResponse.setContentType("application/json;charset=UTF-8");
            servletResponse.getWriter().write(JSONUtils.serialize(ExecuteResultProcessor.accessDenied("该ip被禁止访问")));
            servletResponse.flushBuffer();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 上报可疑事件
     *
     * @param servletRequest
     */
    protected void reportSuspiciousEvent(ServletRequest servletRequest) {

        SuspiciousEvent suspicious = new SuspiciousEvent()
                .setType(Constant.SuspiciousType.ILLEGAL_IP)
                .setTitle("refused ip：" + getClientIP(servletRequest))
                .setLevel(Constant.SuspiciousLevel.ORANGE)
                .setContent(JSONUtils.serialize(new AccessLog("refused ip", servletRequest)))
                .setUserId(SubjectUtils.getCurrentUserId());

        SuspiciousUtils.report(suspicious);
    }
}
